package com.bkitmobile.kesu.android.service;

import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import com.bkitmobile.kesu.android.GUI.FriendsList;
import com.bkitmobile.kesu.android.connectServer.Request;
import com.bkitmobile.kesu.android.connectServer.staticClass;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public class ServiceLocationConnection implements ServiceConnection{
	private UpdateLocationService mBoundService;
	public void onServiceConnected(ComponentName className, IBinder service) {
		//mHandler = new Handler();
        mBoundService = ((UpdateLocationService.UpdateLocationBinder)service).getService();
        if (!staticClass.isFirst){
	        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(4);
			nameValuePairs.add(new BasicNameValuePair("ID", Request.UPDATE_LIST));
			String line = null, result = null;
	    	InputStream is = null;
			try{			
		    	staticClass.httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    	HttpResponse response = staticClass.httpclient.execute(staticClass.httppost);
		    	HttpEntity entity = response.getEntity();
		    	is = entity.getContent();
			} catch (Exception e)
			{
				Log.e("log_tag", "Error connection");
			}
			try {
	    		StringBuffer stringBuffer = new StringBuffer();
	    		char ch;
	    		int c;
	    		while((c=is.read())!=-1){
		    		ch = (char) c;
		    		stringBuffer.append(ch);
	    		}
	    		result = new String(stringBuffer);
	    		result = URLDecoder.decode(result, "UTF-8");
			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
			}
			
			mBoundService.setStringUpdate(result);
        } else staticClass.mHandler.sendEmptyMessage(100);
        if (FriendsList.msg != null)   
        {
        		staticClass.sendToService.sendMessage(FriendsList.msg);
        		FriendsList.msg = null;
        }
		
    }

    public void onServiceDisconnected(ComponentName className) {
        mBoundService = null;
    }
    public UpdateLocationService getService()
    {
    	return mBoundService;
    }
}
